//
//  NvMoreFilterViewController.m
//  SDKDemo
//
//  Created by ms20180425 on 2018/5/29.
//  Copyright © 2018年 meishe. All rights reserved.
//

#import "NvMoreDownloadViewController.h"
#import "NvMoreDownloadItem.h"
#import "NvAssetManager.h"
#import "MJRefresh.h"
#import "NvMoreDownloadTableViewViewCell.h"
#import "NvSDKUtils.h"

@interface NvMoreDownloadViewController ()<UITableViewDelegate, UITableViewDataSource, NvAssetManagerDelegate,NvMoreDownloadCellDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NvMoreDownloadItem *model;

@end

@implementation NvMoreDownloadViewController {
    NvAssetManager *assetManager;
    NSMutableArray *filters;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [NvSDKUtils getMoreTitleName:self.type];
    [self addSubViews];
    // Do any additional setup after loading the view.
    
    filters = NSMutableArray.new;
    assetManager = [NvAssetManager sharedInstance];
    assetManager.delegate = self;
}

- (void)dealloc {
    NSLog(@"%s",__func__);
}

- (void)addSubViews{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[NvMoreDownloadTableViewViewCell class] forCellReuseIdentifier:@"NvMoreDownloadTableViewViewCell"];
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view).offset(0);
        make.width.offset(SCREEN_WDITH);
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self->filters removeAllObjects];
        [self->assetManager downloadRemoteAssetsInfo:self.type aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL page:0 pageSize:NV_FILTER_PAGE_SIZE];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        int page = (int)self->filters.count/NV_FILTER_PAGE_SIZE;
        [self->assetManager downloadRemoteAssetsInfo:self.type aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL page:page pageSize:NV_FILTER_PAGE_SIZE];
    }];
}

#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return filters.count;
}

- (NvMoreDownloadTableViewViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NvMoreDownloadTableViewViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NvMoreDownloadTableViewViewCell"];
    cell.type = self.type;
    cell.indexPath = indexPath;
    cell.delegate = self;
    cell.model = filters[indexPath.row];

    return cell;
}

#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70 * SCREANSCALE;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    [assetManager downloadAsset:[(NvFilterItem *)filters[indexPath.row] package]];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onRemoteAssetsChanged:(BOOL)hasNext {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    [filters removeAllObjects];
    NSArray *array = [assetManager getRemoteAssets:self.type aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        NvMoreDownloadItem *filter = [[NvMoreDownloadItem alloc]init];
        filter.displayName = asset.name;
        filter.cover = [asset.coverUrl absoluteString];
        filter.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
        filter.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
        filter.package = asset.uuid;
        if ([asset isUsable]) {
            if ([asset hasUpdate]) {
                filter.state = MoreDownloadUpdate;
            }else{
                filter.state = MoreDownloadFinish;
            }
        }else{
            filter.state = NOMoreDownload;
        }
        
        [filters addObject:filter];
    }
    [self.tableView reloadData];
}

- (void)onDownloadAssetProgress:(NSString *)uuid progress:(int)progress {
    NSLog(@"%d", progress);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0; i < self->filters.count; i++) {
            NvMoreDownloadTableViewViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            NvMoreDownloadItem *item = cell.model;
            if ([item.package isEqualToString:uuid]) {
                cell.download.progress = progress/100.f;
            }
        }
    });
    
}

- (void)onDonwloadAssetSuccess:(NSString *)uuid {
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0; i < self->filters.count; i++) {
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            NvMoreDownloadTableViewViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            NvMoreDownloadItem *item = cell.model;
            if ([item.package isEqualToString:uuid]) {
                item.state = MoreDownloadFinish;
                NSMutableArray *array = NSMutableArray.new;
                [array addObject:indexPath];
                [self.tableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
            }
        }
    });
}

- (void)nvMoreFilterCell:(NvMoreDownloadTableViewViewCell *)nvMoreFilterCell nvFilterItem:(NvMoreDownloadItem *)nvFilterItem{
    [assetManager downloadAsset:nvFilterItem.package];
}

@end
